package com.lbjhan.rpc.consumer.processor;

import com.google.protobuf.MapEntry;
import com.lbjhan.rpc.consumer.anno.RpcService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ProviderBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    public static final Map<String, Object> SERVICE_INSTANCE_MAP = new ConcurrentHashMap();
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        Map<String, Object> beansWithAnnotation = configurableListableBeanFactory.getBeansWithAnnotation(RpcService.class);
        System.out.println("------------------------------ ProviderBeanFactoryPostProcessor -------------------------------------- ");
        for (Map.Entry<String , Object> item : beansWithAnnotation.entrySet()){
            System.out.println("key : " + item.getKey());
            Object bean = item.getValue();
            Class<?>[] interfaces = bean.getClass().getInterfaces();
            if(interfaces.length == 0){
                throw new RuntimeException("服务必须实现接口...");
            }
            SERVICE_INSTANCE_MAP.put(interfaces[0].getName(), bean);
        }
        System.out.println("------------------------------ ProviderBeanFactoryPostProcessor -------------------------------------- ");
    }
}
